<template>
  <div class="parent">
    <div class="title">
      项目详情
    </div>
    <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
      <div style="display: flex;justify-content: space-between;">
        <div class="title2">概览数据</div>
        <el-button type="primary"
          @click="dialogFormVisible = true; form.alarmModelId = detail.alarmModelId">告警模板变更</el-button>
        <el-dialog v-model="dialogFormVisible" title="告警模板变更">
          <el-form :model="form">
            <el-form-item label="告警模板" :label-width="formLabelWidth">
              <el-select clearable v-model="form.alarmModelId" placeholder="请选择告警模板">
                <el-option v-for="value in alarmModels" :label="value.name + '(' + value.modelNo + ')'"
                  :value="value.id" />
              </el-select>
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="editAlarmModel">
                确认修改
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
      <ElRow :gutter="20">
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>项目编号:<text>{{ detail.projectNo }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>项目名称:<text>{{ detail.projectName }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem" style="display: flex;">
          <div>监控模型:<text>{{ detail.monitorModelNo }}</text>
          </div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>告警模板:<text>{{ detail.alarmModelNo }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>采样频率:<text>{{ detail.projectRate }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>状态:<text>{{ detail.online == "1" ? "在线" : "离线" }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>创建时间:<text>{{ detail.createTime }}</text></div>
        </ElCol>
        <ElCol :xs="24" :sm="12" :md="6" class="elColItem">
          <div>心跳时间:<text>{{ detail.heartTime }}</text></div>
        </ElCol>
      </ElRow>
    </ElCard>
    <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
      <div class="title2" style="display: flex;flex-direction: row;justify-content: space-between;">
        <div>测点数据</div>
        <div><el-date-picker @change="queryMonitorModel()" format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss" v-model="attValueTime" type="datetimerange" range-separator="To"
            start-placeholder="Start date" end-placeholder="End date" /></div>
      </div>
      <ElRow :gutter="20">
        <ElCol v-if="chartShow" :xs="24" :sm="12" :md="8" class="elColItem" v-for="value in attKeyS">
          <div class="card art-custom-card">
            <div class="card-header">
              <span></span>
            </div>
            <ArtLineChart :data="value.y" :xAxisData="value.x" :showLegend="true" />
          </div>
        </ElCol>
      </ElRow>
    </ElCard>
    <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
      <div class="title2">
        元数据
      </div>
      <!-- 表格 -->
      <ArtTable rowKey="id" :show-table-header="false" :loading="data_loading" :data="data_tableData"
        :columns="data_columns" :pagination="data_pagination" @pagination:size-change="data_handleSizeChange"
        @pagination:current-change="data_handleCurrentChange">
      </ArtTable>
    </ElCard>
    <ElCard class="art-table-card" shadow="never" style="margin-top: 20px">
      <div class="title2">
        告警数据
      </div>
      <!-- 表格 -->
      <ArtTable rowKey="id" :show-table-header="false" :loading="alarm_loading" :data="alarm_tableData"
        :columns="alarm_columns" :pagination="alarm_pagination" @pagination:size-change="alarm_handleSizeChange"
        @pagination:current-change="alarm_handleCurrentChange">

        <!-- 告警等级列 -->
        <template #grade="{ row }">
          <div class="">
            <el-tag v-if="row.grade == '1'" style="color:#ffffff" color="red">紧急告警</el-tag>
            <el-tag v-else-if="row.grade == '2'" class="" type="danger">告警</el-tag>
            <el-tag v-else-if="row.grade == '3'" class="" type="warning">预警</el-tag>
            <el-tag v-else class="" type="success">正常</el-tag>
          </div>
        </template>
        <!-- 告警状态列 -->
        <template #status="{ row }">
          <div class="">
            <el-tag v-if="row.status == '1'" style="color:#ffffff" color="red">告警中</el-tag>
            <el-tag v-else class="" type="success">已解除</el-tag>
          </div>
        </template>
      </ArtTable>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { router } from '@/router'
import type { LineDataItem } from '@/types/component/chart'
import { useTable } from '@/composables/useTable'
import { BmslzService } from '@/api/bmslzApi'
import { ElMessage } from 'element-plus'

const route = useRoute();
const projectId = route.query.id as string;
const detail = reactive({
  projectNo: '',
  projectName: '',
  monitorModelNo: '',
  alarmModelNo: '',
  projectRate: '',
  alarmModelId: '',
  online: '',
  createTime: '',
  heartTime: '',
  monitorModelId: '',
})
const dialogTableVisible = ref(false)
const dialogFormVisible = ref(false)
const chartShow = ref(false)

const formLabelWidth = '140px'
const alarmModels = ref<any[]>([]) // 告警模板数组
const monitorModel = ref<any>()//监控模型详情
const attKeyS = ref<any[]>([]) //测点数组

const form = reactive({
  alarmModelId: '',
})

// 格式化时间函数
const formatTime = (date: Date): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

const attValueTime = ref<[string, string]>([
  formatTime(new Date(new Date().getTime() - 30 * 60 * 1000)),
  formatTime(new Date())
])

const {
  tableData: data_tableData,
  columns: data_columns,
  isLoading: data_loading,
  paginationState: data_pagination,
  onPageSizeChange: data_handleSizeChange,
  onCurrentPageChange: data_handleCurrentChange
} = useTable<any>({
  core: {
    apiFn: BmslzService.queryProjectDatas,
    apiParams: {
      projectId: projectId,
      pageSize: 10,
      pageNo: 1,
    },
    paginationKey: {
      current: 'pageNo',
      size: 'pageSize'
    },
    columnsFactory: () => [
      {
        prop: 'attKey',
        label: '测点key'
      },
      {
        prop: 'attName',
        label: '测点名称'
      },
      {
        prop: 'attValue',
        label: '测点值',
      },
      {
        prop: 'heartTime',
        label: '心跳时间'
      },
      {
        prop: 'createTime',
        label: '创建时间'
      }
    ]
  }
})

const {
  tableData: alarm_tableData,
  columns: alarm_columns,
  isLoading: alarm_loading,
  paginationState: alarm_pagination,
  onPageSizeChange: alarm_handleSizeChange,
  onCurrentPageChange: alarm_handleCurrentChange
} = useTable<any>({
  core: {
    apiFn: BmslzService.queryProjectAlarmDatas,
    apiParams: {
      projectId: projectId,
      pageSize: 10,
      pageNo: 1,
    },
    paginationKey: {
      current: 'pageNo',
      size: 'pageSize'
    },
    columnsFactory: () => [
      {
        prop: 'grade',
        label: '等级',
        useSlot: true,
      },
      {
        prop: 'status',
        label: '状态',
        useSlot: true,
      },
      {
        prop: 'attKey',
        label: '测点key',
      },
      {
        prop: 'attName',
        label: '测点名称',
      },
      {
        prop: 'alarmValue',
        label: '告警值'
      },
      {
        prop: 'ruleValue',
        label: '告警规则阈值'
      },
      {
        prop: 'createTime',
        label: '告警时间'
      }
    ]
  }
})

const multiLineData: LineDataItem[] = [
  {
    lineColor: "red",
    name: '告警阈值',
    data: [80, 80, 80, 80, 80, 80],
    areaStyle: {
      startOpacity: 0.1,
      endOpacity: 0
    }
  },
  {
    name: '测点名称',
    data: [80, 92, 71, 94, 60, 80],
    areaStyle: {
      startOpacity: 0.1,
      endOpacity: 0
    }
  }
]


onMounted(async () => {
  queryById()
});
// 查询详情
const queryById = async () => {
  try {
    //查询模板详情
    const data = await BmslzService.projectDetail({
      id: projectId,
    })
    if (!data) {
      ElMessage.error('项目不存在');
      router.go(-1); // -1 表示返回上一页
    }
    detail.projectNo = data.projectNo
    detail.projectName = data.projectName
    detail.monitorModelNo = data.monitorModelNo
    detail.monitorModelId = data.monitorModelId
    detail.alarmModelNo = data.alarmModelNo
    detail.alarmModelId = data.alarmModelId
    detail.projectRate = data.projectRate
    detail.online = data.online
    detail.createTime = data.createTime
    detail.heartTime = data.heartTime
    queryCanUseAlarmModel()
    queryMonitorModel()
  } catch (err) {
  } finally {
  }
};
//查询监控模型详情
const queryMonitorModel = async () => {
  chartShow.value = false
  const data = await BmslzService.monitorModelQueryById({
    id: detail.monitorModelId,
  })

  monitorModel.value = data;
  attKeyS.value = JSON.parse(data.att);

  //装配历史数据进去
  for (var val in attKeyS.value) {
    //当前key的历史数据
    const res = await queryAttValueList(attKeyS.value[val].attKey);
    //当前key的告警规则
    const ruleRes = await queryRuleByKey(attKeyS.value[val].attKey);
    let x1: any[] = []
    let y2: any[] = []
    res.forEach((element: { x: any; y: any }) => {
      x1.push(element.x)
      y2.push(element.y)
      ruleRes.forEach((rule: any) => {
        if (!rule.arr) {
          rule.arr = [];
        }
        rule.arr.push(rule.dataValue)
      });
    });
    console.log(ruleRes, "ruleResruleResruleRes")
    let yItems: any = [
      {
        name: attKeyS.value[val].attName,
        data: y2,
        areaStyle: {
          startOpacity: 0.1,
          endOpacity: 0
        }
      }
    ]
    ruleRes.forEach((rule: any) => {
      let ruleName = ''
      let ruleColor = '';
      if (rule.grade == '3') {
        ruleName = '告警线（预警）'
        ruleColor = 'yellow'
      } else if (rule.grade == '2') {
        ruleName = '告警线（告警）'
        ruleColor = 'orange'
      } else {
        ruleName = '告警线（紧急）'
        ruleColor = 'red'
      }
      yItems.push(
        {
          lineColor: ruleColor,
          name: ruleName,
          data: rule.arr,
          areaStyle: {
            startOpacity: 0.1,
            endOpacity: 0
          }
        }
      )
    });
    attKeyS.value[val].x = x1;
    attKeyS.value[val].y = yItems;
  }
  console.log("图标", attKeyS.value)
  chartShow.value = true;
}

// 查询单个测点历史数据
const queryAttValueList = async (key: any) => {
  try {
    //查询模板详情
    const data = await BmslzService.queryAttValueList({
      projectId: projectId,
      times: attValueTime.value,
      attKey: key
    })
    return data;
  } catch (err) {
  } finally {
  }
};
// 根据项目id和key查找告警规则
const queryRuleByKey = async (key: any) => {
  try {
    //查询模板详情
    const data = await BmslzService.queryRuleByKey({
      projectId: projectId,
      attKey: key
    })
    return data;
  } catch (err) {
  } finally {
  }
};
// 查询可用告警模板
const queryCanUseAlarmModel = async () => {
  const data = await BmslzService.alarmModelList({
    pageNo: 1,
    pageSize: 9999,
    monitorModelId: detail.monitorModelId
  })

  alarmModels.value = data.records
};

// 修改项目的告警模板
const editAlarmModel = async () => {
  const data = await BmslzService.editProjectAlarmModel({
    alarmModelId: form.alarmModelId,
    projectId
  })
  ElMessage.success('操作成功！');
  dialogFormVisible.value = false
  queryById();
};
</script>

<style lang="scss" scoped>
.parent {
  padding: 0 0 0 20px;

  .title {
    color: #101010;
    font-size: 20px;
    font-weight: bold;
  }

  .title2 {
    color: #101010;
    font-size: 15px;
    font-weight: bold;
  }
}

.elColItem {
  padding-top: 20px;
  font-size: 14px;
}
</style>
